package artibella.ui.forms
{
	import artibella.IDisposable;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	
	/**
	 * ...
	 * @author pbordachar
	 */
	
	public class RadioButtons_Group extends Sprite implements IDisposable
	{
		private var _selectedIndice:int;
		private var _tab:Array;
		
		public function RadioButtons_Group() 
		{
			_init();
		}
		
		private function _init():void
		{
			_selectedIndice = -1;
			_tab = new Array();
		}
		
		// - - -
		
		public function addItem( c:ARadioButton, selected:Boolean = false ):void
		{
			addChild( c );
			
			_tab.push( c );
			
			c.indice = _tab.length - 1;
			
			if ( selected && _selectedIndice < 0 ) {
				_selectedIndice = c.indice;
				c.doClick();
			}
		}
		
		public function finalize():void
		{
			addEventListener( MouseEvent.ROLL_OVER, _doRollOver, true );
			addEventListener( MouseEvent.ROLL_OUT, _doRollOut, true );
			addEventListener( MouseEvent.CLICK, _doClick, true );
			
			if ( _selectedIndice < 0 ) {
				throw new Error( "no radio button selected" );
			} else {
				_checkItems();
			}
		}
		
		// - - -
		
		private function _doRollOver( e:MouseEvent ):void
		{
			var item:ARadioButton = e.target as ARadioButton;
			item.doRollOver();
		}
		
		private function _doRollOut( e:MouseEvent ):void
		{
			var item:ARadioButton = e.target as ARadioButton;
			item.doRollOver();
		}
		
		private function _doClick( e:MouseEvent ):void
		{
			var item:ARadioButton = e.target as ARadioButton;
			item.doClick();
			
			_selectedIndice = item.indice;
			_checkItems();
		}
		
		// - - -
		
		private function _checkItems():void
		{
			for ( var i:int = 0; i < _tab.length; i ++ ) {
				var item:ARadioButton = _tab[ i ] as ARadioButton;
				if ( item.indice != _selectedIndice ) {
					item.undoClick();
				}
			}
		}
		
		// - - -
		
		public function get selected():int
		{
			return _selectedIndice;
		}
		
		// - - - IDisposable
		
		public function dispose():void
		{
			removeEventListener( MouseEvent.ROLL_OVER, _doRollOver, true );
			removeEventListener( MouseEvent.ROLL_OUT, _doRollOut, true );
			removeEventListener( MouseEvent.CLICK, _doClick, true );
			
			_tab = null;
		}
	}
}